package com.summer.safe.controller.system;

import com.summer.safe.base.BaseController;
import com.summer.safe.base.Page;
import com.summer.safe.config.annotation.ResultWrapper;
import com.summer.safe.config.result.ResultCode;
import com.summer.safe.system.entity.Dict;
import com.summer.safe.system.entity.DictType;
import com.summer.safe.system.service.DictService;
import com.summer.safe.system.service.DictTypeService;
import com.summer.safe.utils.Global;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * 字典管理Controller
 *
 */
@Controller
@RequestMapping(value = "/sys/dict")
public class DictController extends BaseController {

    private String PREFIX = "/system/dict/";
    @Autowired
    private DictService dictService;

    @Autowired
    private DictTypeService dictTypeService;

    @ModelAttribute("dict")
    public Dict get(@RequestParam(required=false) String id) {
        if (StringUtils.isNotBlank(id)){
            return dictService.get(id);
        }else{
            return new Dict();
        }
    }


    /**
     * 字典类型详情
     * @param model
     * @return
     */
    @GetMapping("/list")
    public String index(Model model,String parentId) {

        model.addAttribute("parentId",parentId);
        return  PREFIX+"data/datalist.html";
    }

    /**
     * 字典类型详情
     * @param dict
     * @param request
     * @return
     */
    @RequestMapping("/dataList")
    @ResultWrapper
    public Page list(Dict dict, HttpServletRequest request) {

        Page<Dict> page = dictService.findPage(new Page(request), dict);
        return page;
    }

    /**
     * 字典类型详情
     * @param dict
     * @param model
     * @return
     */
    @GetMapping("/form")
    public String form(Dict dict, Model model) {

        if(dict.getOp().equals(Global.OP_ADD)){
            DictType dictType=dictTypeService.get(dict.getParent().getId());
            dict.setType(dictType.getType());
            dict.setDescription(dictType.getRemarks());
        }
        model.addAttribute("dict", dict);
        return PREFIX+"data/dataform.html";
    }




    /**
     *字典类型详情
     * @param dict
     */
    @PostMapping("/save")
    @ResultWrapper(ResultCode.SUCCESS_SAVE)
    public void save(Dict dict) {
        dictService.save(dict);
    }


    /**
     * 字典类型详情
     * @param dict
     */
    @PostMapping("/delete")
    @ResultWrapper(ResultCode.SUCCESS_DELETE)
    public void delete(Dict dict) {
        dictService.delete(dict);
    }
}